package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"github.com/gpmgo/gopm/modules/log"
	"fmt"
)

type Product struct {
	gorm.Model
	Code string
	Price uint
	Name string `gorm:"type:varchar(100);not null;column:product_name"` // 定义表中的字段名为product_name
}

var Sqlite *gorm.DB

func init() {
	db, err := gorm.Open("sqlite3", "test.db")
	if err != nil {
		panic("failed to connect database")
	}
	Sqlite = db
}

func main() {
	Sqlite.AutoMigrate(&Product{})
	CreateDBData()
	defer Sqlite.Close()
}

//  添加数据
func CreateDBData() {
	nameList := []string{"1", "2", "3", "4", "5"}
	for index, name := range nameList {
		var product Product
		product = Product{
			Code:"code:" + name,
			Price:uint(index),
		}
		Sqlite.Create(&product)
	}
}

//  基础查找
func Find(value string) {
	var product Product
	dbError := Sqlite.Where("id = ?", value).First(&product).Error; if dbError != nil {
		log.Error(dbError.Error())
		return
	}
	fmt.Println(product)
}
//  基础更新
func Update(id string, value string) {
	var product Product

	dbErr := Sqlite.Where("id = ?", id).First(&product).Error; if dbErr != nil {
		fmt.Println(dbErr.Error())
		return
	}

	dbErr = Sqlite.Model(&product).Update("code", value).Error; if dbErr != nil {
		fmt.Println(dbErr)
		return
	}
	fmt.Println("new", product)
}
